package com.benshou.bsoa.common.quartz;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
@Slf4j
public class JobCleanupService{

    @Resource
    private Scheduler scheduler;
    @Resource
    private QuartzJobScanner quartzJobScanner;
    /**
     * 清理未定义的 Job
     */
    public void cleanupUndefinedJobs() throws SchedulerException {
        // 获取所有已定义的 Job
        Set<JobKey> definedJobKeys = quartzJobScanner.getDefinedJobKeys();

        // 获取数据库中所有的 Job
        Set<JobKey> allJobKeys = scheduler.getJobKeys(GroupMatcher.anyGroup());

        for (JobKey jobKey : allJobKeys) {
            if (!definedJobKeys.contains(jobKey)) {
                try {
                    scheduler.deleteJob(jobKey); // 删除未定义的 Job
                } catch (SchedulerException e) {
                    // 清除异常忽略
                }
            }
        }
    }

}